/* eslint-disable array-callback-return */
/* eslint-disable no-case-declarations */
// Import Swiper React components
import { useState, useMemo, useRef, useEffect } from 'react';
import {
  LoadingOutlined,
  PictureFilled,
  PlusOutlined,
  QrcodeOutlined,
  UserAddOutlined,
} from '@ant-design/icons';
import {
  Avatar,
  Button,
  message,
  FloatButton,
  Progress,
  theme,
  Tooltip,
  Tag,
  Popover,
  Row,
  Col
} from 'antd';
import Limit from '../Limit';
// Import Swiper styles
import { difftime, difftimes } from '@/utils/time';
import dayjs from 'dayjs';
import { Zoom } from 'react-reveal';
import DragModal from '../DragModal';
import { ProFormSelect } from '@ant-design/pro-components';
import useCurrentUser from '@/utils/useCurrentUser';
import './index.less';
import { useRequest } from 'ahooks';
import { doFetch, getFetch } from '@/utils/doFetch';
import { Badge } from 'antd';
import useMyProjectList from '@/utils/useMyProjectList';
import { toPng } from 'html-to-image';
import useProjectList from '@/utils/useProjectList';
import Tagpreview from '../Tagadder/tagpreview';
import { statusConf } from '@/utils/global'
import { v4 as uuidv4 } from 'uuid';
import ItemCard from '../ItemCard';
import IconFont from '../IconFont';
import FileCard from '../FileCard';


const Users = ({ project = {}, activeUserIdList = [], token, readonly, data }) => {
  const [addusers, setAddusers] = useState([]);


  //按钮 loading
  const { run, loading, runAsync } = useRequest(doFetch, {
    onSuccess: (res) => {
      if (res?.code === 0) {
        refresh();
        setAddusers([]);
        setModal(s => ({
          ...s,
          open: false
        }))
      }
    }
  });



  const [modal, setModal] = useState({
    title: <div className='centerl'>
      <UserAddOutlined style={{ fontSize: 18, marginRight: 3 }} />
      添加人员
    </div>,
    open: false,
    width: 380,
    onCancel: () => {
      setAddusers([]);
      setModal(s => ({
        ...s,
        open: false
      }))
    }
  });

  //优化操作
  const [open, setOpen] = useState(false);


  const formatdata = useMemo(() => data ? [
    data?.find((it) => it?.id === project?.projectUserId),
    ...[
      ...data?.filter(
        (it) =>
          it?.id !== project?.projectUserId && activeUserIdList.includes(it?.id.toString()),
      ),
      ...data?.filter(
        (it) =>
          it?.id !== project?.projectUserId && !activeUserIdList.includes(it?.id.toString()),
      ),
    ],
  ] : [], [data])

  return <div>
    <DragModal
      {...modal}
      footer={[
        <Button key='cancel' onClick={() => {
          setModal(s => ({
            ...s,
            open: false
          }))
        }}>取消</Button>,
        <Button key='ok' type='primary' loading={loading} onClick={async () => {
          let res = await runAsync({
            url: '/project/' + project?.id,
            params: {
              userIdList: [...data?.map(item => item?.id), ...addusers],
            },
            method: 'PUT',
          });
        }}>确定</Button>
      ]}
    >
      <ProFormSelect
        params={{ projectId: project?.id }}
        value={addusers}
        style={{ marginTop: 6 }}
        onChange={setAddusers}
        mode='multiple'
        fieldProps={{
          maxTagCount: 3
        }}
        request={async ({ projectId }) => {
          let res = await getFetch({ url: "/user/outsideProjectUser", params: { projectId } });
          return res?.data?.dataList;
        }}
      />
    </DragModal>

    {
      loading ?
        <div
          className='griders'
        >
          <div style={{ height: 80, width: 80 }}>
            <Avatar size='small' icon={<LoadingOutlined />} style={{ flexShrink: 0 }}></Avatar>
          </div>
        </div>
        : <div style={{ display: 'flex' }}>
          <div
            className='griders'
          >
            {data?.length > 0 && formatdata.map((it, i) => {
              const isMine = it?.isMaster === 1; //it?.id === project?.projectUserId;
              return <div key={it?.id} style={{ backgroundColor: token.colorOppsites }}>
                <Badge count={isMine ? <IconFont type='icon-manager' rotate={30} /> : 0}>
                  <Avatar
                    src={it?.headUrl}
                    size={"default"}
                    style={{
                      // filter:
                      //   activeUserIdList.indexOf(it.id.toString()) !== -1 ||
                      //   currentUser?.id === it.id
                      //     ? 'grayscale(0%)'
                      //     : 'grayscale(100%)',
                      cursor: 'pointer',
                      backgroundColor: token.colorBgContainer,
                      color: token.colorText,
                    }}
                  >
                    {it?.name?.charAt(0)}
                  </Avatar>
                </Badge>
                <div className="columns" style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
                  <span className='oneline' style={{ padding: "0 4px" }}>
                    {it?.name}
                  </span>
                  <Tag style={{ margin: 0 }}>
                    {it?.projectRoleId === 2 ? '服务' : it?.projectRoleId === 3 ? '审批' : '-'} {it?.points}分
                  </Tag>
                </div>
              </div>
            })}

            {
              !readonly && <div >
                <Avatar icon={<PlusOutlined />} onClick={() => {
                  setOpen(false);
                  setModal(s => ({
                    ...s,
                    open: true
                  }))
                }}></Avatar>
              </div>
            }


          </div>
        </div>
    }
  </div>
}


let col = { xs: 24, sm: 24, md: 12, lg: 6, xl: 6, xxl: 4 },
  colc = { xs: 24, sm: 12, md: 8, lg: 6, xl: 4, xxl: 4 },
  cols = { xs: 24, sm: 24, md: 24, lg: 12, xl: 12, xxl: 16 },
  cold = { xs: 24, sm: 24, md: 24, lg: 12, xl: 12, xxl: 6 };



const ProjectDetail = ({ curid }) => {
  const domRef = useRef();
  const [iscopy, setIscopy] = useState(false);
  const handleCopyImage = async () => {
    setIscopy(true);
    try {
      setTimeout(async () => {
        const dataUrl = await toPng(domRef.current, { pixelRatio: 2 });
        const blob = await fetch(dataUrl).then((res) => res.blob());
        const clipboardItem = new ClipboardItem({ 'image/png': blob });
        await navigator.clipboard.write([clipboardItem]);
        message.success('图片已复制到剪贴板');
        setIscopy(false)
      }, 20);
    } catch (error) {
      message.error('复制图片失败：', error);
      setIscopy(false)
    }
  };
  const { setInitialState } = useCurrentUser();
  const { token } = theme.useToken();
  const {
    colorText,
    colorPrimary,
    colorBgThird,
    colorBgFourth,
    colorBgContainer,
    colorOppsites
  } = token;

  const { initialState: { activeUserIdList, currentUser }, proList } = useProjectList();


  const { data, loading } = useRequest(async () => {
    let res = await getFetch({ url: "/project/detail/" + curid, params: {} });
    return res?.data?.data;
  }, {
    refreshDeps: [curid],
  })

  const it = useMemo(() => {
    return data ?? {};
  }, [data])

  const style = {
    backgroundColor: colorOppsites,
    cursor: 'default',
    gap: 6,
    justifyContent: 'center',
    padding: 16,
    overflow: 'hidden',
    display: 'flex',
    borderRadius: 8,
    fontSize: 14,
    backdropFilter: "blur(4px)",
    width: "100%",
    height: "100%"
  }

  const strokeColor = useMemo(() => {
    return currentUser.theme === 'light' ? {
      "0%": '#fec163',
      '70%': '#ff4800',
    } : {
      "0%": '#17ead9',
      '70%': '#6078ea',
    }
  }, [currentUser.theme]);


  //更新数据
  const { runAsync } = useRequest(doFetch, {
    manual: true,
    debounceWait: 400,
    onSuccess: (res) => {
      if (res.code === 0) {
        setInitialState(s => ({
          ...s,
          updateProject: uuidv4(),
        }))
      }
    }

  })

  useEffect(() => {
    if (!it?.id) return;
    const curproj = proList.find(p => p.id === it.id);
    if (!curproj) return;
    if (curproj.status !== it.status) {
      setInitialState(s => ({
        ...s,
        curpro: {
          ...curproj
        }
      }))
    }
  }, [proList, it]);



  return (
    <div style={{ marginBottom: 12 }}>
      <div
        ref={domRef}
        style={{
          width: '100%',
          background: iscopy ? colorBgContainer : 'transparent',
          borderRadius: 12,
          color: colorText
        }}
      >
        <div className="columns" style={{
          gap: 16,
          padding: iscopy ? 20 : 0,
        }}>
          <Row gutter={[16, 16]}>
            <Col {...col} className='center'>
              <div
                style={{ ...style }}
              >
                <div style={{ position: "relative", paddingTop: 18 }} className='center columns gap12'>
                  <div className="columns" style={{ width: "100%", justifyContent: "flex-start", alignItems: "center" }}>
                    <Avatar
                      src={it?.logoUrl}
                      onClick={async (e) => {
                        e.stopPropagation();
                      }}
                      shape="square"
                      size={126}
                      style={{ flexShrink: 0, borderRadius: 16 }}
                    >
                      {it?.projectName?.charAt(0)}
                    </Avatar>

                    <b style={{ display: "block", height: 30, lineHeight: "30px", fontSize: 16, marginTop: 12 }}>{it?.projectName}</b>

                    <Tooltip placement='bottomLeft' title={it?.createTime}>
                      <p style={{ opacity: 0.5, fontSize: 12, width: "100%", margin: 0, textAlign: "center" }}>{it?.createUserName}创建于{difftime(dayjs(), dayjs(it?.createTime))}</p>
                    </Tooltip>
                  </div>
                  <Tag color={statusConf[it?.status]?.color}>项目状态 - {statusConf[it?.status]?.text}</Tag>
                </div>
              </div>
            </Col>
            <Col {...col}>
              <div className="columns" style={{ gap: 12, overflow: 'hidden', height: "100%" }}>
                <div style={{ ...style, justifyContent: "flex-start", alignItems: "flex-start", flexDirection: "column", height: "auto", gap: 10 }}>
                  <div className="spread" style={{ width: "100%" }}>
                    <b>
                      项目积分
                    </b>
                    <Tag color={colorPrimary} style={{ margin: 0 }}>
                      共 {it?.points} 分
                    </Tag>
                  </div>
                  <div className="spread" style={{ width: "100%" }}>
                    <b style={{ color: '#999', fontSize: 12 }}>
                      已分配:
                      <span style={{ color: colorText, fontSize: 14 }}> {it?.assignPoints} </span>分
                    </b>
                    <b style={{ color: '#999', fontSize: 12 }}>
                      未分配:
                      <span style={{ color: colorText, fontSize: 14 }}> {it?.points - it?.assignPoints} </span>分
                    </b>
                  </div>
                  <div className="spread" style={{ width: "100%", borderRadius: 66, marginBottom: 10, height: 4, borderRadius: 4, overflow: "hidden" }}>
                    <div style={{ borderRadius: 4, height: 4, width: `${parseInt(it.assignPoints / (it.points) * 100)}%`, background: it.points === 0 ? colorBgFourth : `linear-gradient(135deg,${strokeColor['0%']},${strokeColor['70%']})` }}>
                    </div>
                    <div style={{ height: 4, width: `${100 - parseInt(it.assignPoints / (it.points) * 100)}%`, backgroundColor: it.points === 0 ? colorBgFourth : colorBgThird }}>
                    </div>
                  </div>
                </div>

                <div style={{ ...style, gap: 4, justifyContent: "center", alignItems: "flex-start", height: "auto" }} className='columns'>
                  <div className="spread" style={{ width: "100%" }}>
                    <b>已完成任务</b>
                    <b style={{ fontSize: 12, opacity: 0.8 }}>
                      {it.finishItemCount}/{it.allItemCount}
                    </b>
                  </div>
                  <Progress
                    style={{ margin: 0, opacity: 0.7 }}
                    percent={it.allItemCount !== 0 ? parseInt(it.finishItemCount * 100 / it.allItemCount) : 0}
                    showInfo={false}
                    size="small"
                    strokeColor={strokeColor}
                  />
                </div>

                <div
                  style={{
                    ...style,
                    flex: 1,
                    justifyContent: "flex-start",
                    alignItems: "flex-start",
                    gap: 10
                  }}
                  className="columns"
                >
                  <div className="spread" style={{ width: '100%', fontSize: 12 }}>
                    <span>截止日期</span>
                    <span>{difftimes(dayjs(it?.deadline), dayjs(), it?.status === 3 ? 0 : it?.status)}</span>
                  </div>
                  <b style={{ display: "block", height: 30, lineHeight: "30px", fontSize: 14 }}>
                    {it.deadline}
                  </b>
                </div>
              </div>
            </Col>
            <Col {...cols}>
              <div style={{ ...style, width: "100%", flexDirection: "column", justifyContent: "flex-start" }}>
                <b>
                  项目标准
                </b>
                <Limit
                  content={it?.notice || '暂无公告'}
                  style={{ width: "100%", height: 'auto' }}
                  onChange={async (value) => {
                    setInitialState(s => ({
                      ...s,
                      curpro: {
                        ...s.curpro,
                        notice: value
                      }
                    }))
                    await runAsync({
                      url: '/project/' + it?.id,
                      params: { notice: value },
                      method: 'PUT',
                    });
                  }}
                ></Limit>
              </div>
            </Col>
          </Row>

          <h2 className="ltitle">
            节点任务
          </h2>
          <Row gutter={[12, 12]}>
            {
              it?.itemList?.map((it, i) => {
                return <Col key={i} {...colc}>
                  {
                    <ItemCard item={it} bg={colorOppsites}></ItemCard>
                  }
                </Col>
              })
            }
          </Row>


          {
            it?.fileList?.length > 0 &&
            <h2 className="ltitle">
              全部文件
            </h2>
          }


          <Row gutter={[12, 12]}>
            {
              it?.fileList?.map((it, i) => {
                return <Col key={i} {...cold}>
                  {
                    <FileCard common item={it} />
                  }
                </Col>
              })
            }
          </Row>

          <h2 className="ltitle">
            参与人员
          </h2>
          <Users readonly={true} project={it} token={token} activeUserIdList={activeUserIdList} data={it?.userList} currentUser={currentUser}></Users>
        </div>
      </div>
    </div>

  );
};

export default ProjectDetail
